import 'dart:io';

import 'package:cunyutech_flutter_core/cunyutech_flutter_core.dart' hide FutureCallbackFunction;
import 'package:device_info/device_info.dart';
import 'package:imei_plugin/imei_plugin.dart';
import 'package:package_info/package_info.dart';

class ApplicationInfo {
  /// 本地版本号
  String localVersion;
  /// 构建号
  int buildVersion;
  /// 手机品牌
  String brand;
  /// 操作系统版本号
  String systemVersion;
  /// 手机型号
  String model;
  /// 操作系统
  String operatingSystem;
  /// 操作系统版本号
  String operatingSystemVersion;
  /// 本地唯一标示 - 本地生成
  String cyid;
  /// 手机唯一标示 - 如果未获取到权限可能获取不到值 双卡双待可能根据网络的不同获取到的imei值也不同
  String imei;
  /// 包名
  String packageName;
  /// App显示名称
  String appName;

  String get id {
    return imei ?? cyid;
  }

  Future init() async {
    await Future.wait([
      _genPackageInfo(),
      _genPhoneInfo(),
      _genId(),
    ]);
  }

  Future _genPackageInfo() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    localVersion = packageInfo.version;
    buildVersion = int.tryParse(packageInfo.buildNumber);
    operatingSystem = Platform.operatingSystem;
    operatingSystemVersion = Platform.operatingSystemVersion;
    packageName = packageInfo.packageName;
    appName = packageInfo.appName;
  }

  Future _genPhoneInfo() async {
    DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    if(Platform.isAndroid) {
      AndroidDeviceInfo androidInfo = await deviceInfo.androidInfo;
      brand = androidInfo.brand;
      systemVersion = androidInfo.version.release;
      model = androidInfo.model;
    } else {
      IosDeviceInfo iosDeviceInfo = await deviceInfo.iosInfo;
      systemVersion = iosDeviceInfo.systemVersion;
      brand = "APPLE";
      model = iosDeviceInfo.model;
    }
  }

  Future _genId() async {
    /// 生成唯一标示
    Directory directory = await CYPath.instance.extStorageDir;
    File cyidFile = File("${directory.path}/cyid.data");
    if(cyidFile.existsSync()) {
      cyid = cyidFile.readAsStringSync();
    } else {
      String md5 = generateMd5("${directory.path}/cyid.data_${DateTime.now().millisecondsSinceEpoch}");
      cyid = md5;
      cyidFile.writeAsStringSync(cyid);
    }
    imei = await ImeiPlugin.getImei( shouldShowRequestPermissionRationale: false );
  }

  Map<String, dynamic> get phoneInfo {
    return {
      "brand": brand,
      "osVersion": systemVersion,
      "phoneModel": model,
    };
  }

  Map<String, dynamic> toJson() {
    return {
      "cyid": cyid,
      "imei": imei,
      "localVersion": localVersion,
      "buildVersion": buildVersion,
      "operatingSystem": operatingSystem,
      "operatingSystemVersion": operatingSystemVersion,
      "brand": brand,
      "osVersion": systemVersion,
      "phoneModel": model,
    };
  }
}